package com.ruoyi.onlyoffice.service;


import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.onlyoffice.config.OnlyProperties;
import com.ruoyi.onlyoffice.domain.OnFile;
import com.ruoyi.onlyoffice.handler.SaveFileProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @BelongsProject: onlyoffice-demo
 * @BelongsPackage: com.oo.demo.service
 * @Author: TongHui
 * @CreateTime: 2023-08-01 16:00
 * @Description: TODO
 * @Version: 1.0
 */
@Service
public class DemoService implements SaveFileProcessor {

    @Autowired
    private OnlyProperties onlyProperties;
    @Autowired
    private IOnFileService onFileService;



    @Override
    public void saveBeforeInitialization(Map<String, Object> map, byte[] bytes, String fileExtension) throws Exception {

    }

    @Override
    public void save(Map<String, Object> map, byte[] file, byte[] changes, String key){
        String fileId = "";
        //获取源文件reportId
        String reportId = onFileService.selectOnFileById((String)map.get("fileId")).getReportId();
        try {
          fileId =   onFileService.saveFile(file,map.get("fileType").toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        //最大报告编号
        String version = onFileService.selectMaxVersion(reportId);
        String[] split = version.split("\\.");
        version = split[0]+"."+split[1]+"."+ (Integer.valueOf(split[2])+1);

        OnFile onFile = new OnFile();
        onFile.setFileId(fileId);
        onFile.setFileName(map.get("fileName").toString());
        if(map.get("reportId")!= null) {
            onFile.setReportId(map.get("reportId").toString());
        }
        onFile.setVersion(version);
        onFile.setFileSize((long) file.length);
        onFile.setFileType(map.get("fileType").toString());
        onFile.setReportId(reportId);
        onFile.setCreatedTimes(DateUtils.formatDate(DateUtils.getNowDate(), DateUtils.YYYY_MM_DD_HH_MM_SS));
        onFileService.insertOnFile(onFile);
        //更新报告数据
        onFileService.updateFileIdByReportId(onFile);
    }

    @Override
    public void saveAfterInitialization(Map<String, Object> map, byte[] bytes, String fileExtension) throws Exception {

    }

}
